package com.ruoyi.iot.service.impl;

import com.ruoyi.iot.service.MqttMessageSender;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MqttMessageSenderImpl implements MqttMessageSender {

    @Resource
    private MqttClient mqttClient;

    @Override
    public void send(String topic, String payload) {
        send(topic, payload, 0, false);
    }

    @Override
    public void send(String topic, String payload, int qos, boolean retained) {

        MqttMessage message = new MqttMessage(payload.getBytes());
        message.setQos(qos);
        message.setRetained(retained);
        try {
            mqttClient.publish(topic, message);
            log.info("发送mqtt消息成功:{}", payload);
        } catch (MqttException e) {
            log.error("发送mqtt消息失败", e);
        }
    }
}
